package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Question;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IAnswerService;
import cn.wolfcode.trip.base.service.IQuestionCommentService;
import cn.wolfcode.trip.base.service.IQuestionService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("questions")
public class QuestionController {

    @Autowired
    private IQuestionService questionService;

    @Autowired
    private IQuestionCommentService questionCommentService;

    @Autowired
    private IAnswerService answerService;

    @PostMapping
    public JSONResult saveOrUpdate(Question question){
        questionService.saveOrUpdate(question);
        return new JSONResult();
    }

    @GetMapping
    public PageInfo<Question> listTQuestions(QueryObject qo){
        //按照创建时间倒序
        qo.setOrderBy("q.createTime desc");
        return questionService.query(qo);
    }

    @GetMapping("/{id}")
    public Question getById(@PathVariable Long id){
        Question question = questionService.getById(id);
        question.setCommentCount(answerService.getCommentCountByQuestionId(id));
        question.setAnswerCount(answerService.getAnswerCountByQuestionId(id));
        return question;
    }

    @GetMapping("/{id}/comments/counts")
    public int getCommentCountById(@PathVariable Long id){
        return questionCommentService.getCommentCountByQuestionId(id);
    }

    @PutMapping("/{id}/addviews")
    public void updateView(@PathVariable Long id){
        questionService.updateView(id);
    }
}
